﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Logic.ClarizenSvc;
using Logic;
using Logic.ClarizenObjects;

namespace ClarizenGadget.Controllers
{
    public class ResourcesController : Controller
    {
        [HttpPost]
        public ActionResult Create(String taskID, String userID)
        {
            var resource = new GenericEntity
            {
                Id = new EntityId
                {
                    TypeName = "ResourceLink"
                },
                Values = new FieldValue[]
                {
                    new FieldValue {FieldName="Resource", Value = new EntityId {TypeName="User", Value=userID}},
                    new FieldValue {FieldName="WorkItem", Value = new EntityId {TypeName="WorkItem", Value=taskID}},
                }
            };
            try
            {
                var id = new QueryComponent().CreateEntity(resource);
                return Json(new GadgetResponse<EntityId> { Data = id, Status = GadgetResponseStatus.Success });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }
        [HttpPost]
        public ActionResult Delete(string resourceID)
        {
            try
            {
                new QueryComponent().DeleteEntity(new EntityId { TypeName = "RegularResourceLink", Value=resourceID});
                return Json(new GadgetResponse<Boolean> { Data = true, Status = GadgetResponseStatus.Success });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }

        [HttpPost]
        public ActionResult Update(List<RegularResourceLink> resources, string taskID)
        {
            try
            {
                var updates = resources.Select(r =>
                    {
                        return !string.IsNullOrEmpty(r.ID.Value) ?
                                (BaseMessage)new UpdateMessage { Entity = r.ToGenericEntity() } :
                                new CreateMessage { Entity = r.ToGenericEntity() };
                    }).ToArray();
                var res = new QueryComponent().Execute(updates);

                Task retValue = Task.GetTask(taskID);

                return Json(new GadgetResponse<Object> { Status = GadgetResponseStatus.Success, Data = retValue });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }

    }
}
